<template>
  <div class="profile-container">
    <a-card title="个人信息管理" :bordered="false">
      <!-- 头像上传 -->
      <div class="avatar-section">
        <div class="avatar-uploader">
          <a-upload name="avatar" list-type="picture-card" class="avatar-upload" :show-upload-list="false"
            :before-upload="beforeAvatarUpload" :custom-request="handleAvatarUpload">
            <img v-if="form.avatar" :src="form.avatar" alt="头像" class="avatar" />
            <div v-else>
              <plus-outlined />
              <div class="upload-text">上传头像</div>
            </div>
          </a-upload>
        </div>
      </div>

      <!-- 个人信息表单 -->
      <a-form :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" @finish="handleSubmit">
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="form.nickname" placeholder="请输入昵称" />
        </a-form-item>

        <a-form-item label="性别" name="sex">
          <a-radio-group v-model:value="form.sex">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="2">女</a-radio>
            <a-radio :value="3">保密</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="form.phone" placeholder="请输入手机号">
          </a-input>
        </a-form-item>


        <a-form-item label="所在地区" name="region">
          <a-cascader v-model:value="form.region" :options="regionOptions" placeholder="请选择省市区" />
        </a-form-item>

        <a-form-item label="收货地址" name="address">
          <a-textarea v-model:value="form.address" placeholder="请输入收货地址" :rows="3" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 6, span: 14 }">
          <a-button type="primary" html-type="submit" :loading="loading">保存修改</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { regionData } from 'element-china-area-data';
import { getUserInfo,updateUserInfo } from '../../../apis/user/user';

import {useUserInfo} from '@/store/useUserInfo';

const user = useUserInfo()
// 表单数据
const form = reactive({
  avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
  nickname: '用户昵称',
  sex: 1,
  phone: '13800138000',
  region: [],
  address: ''
});

// 地区选择选项
const regionOptions = ref(regionData);

// 加载状态
const loading = ref(false);


// 初始化数据
onMounted(() => {
  fetchUserProfile();
});

// 获取用户信息
const fetchUserProfile = async () => {
  try {
    // 模拟API调用
    const res = await getUserInfo();
    let address = '';
    let region = [];
    if(res.data.address){
      address = JSON.parse(res.data.address);
      if(Array.isArray(address) && address.length >=4){
        region = address.slice(0,3);
        address = address.slice(3,4)
      }
    }
 
   
    const data = {
      ...res.data,
      region,
      address
    }
    Object.assign(form, data);
    user.setUserInfo(data)
  } catch (error) {
    message.error('获取用户信息失败');
  }
};

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.includes('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!');
    return false;
  }

  return true;
};

// 自定义头像上传
const handleAvatarUpload = async ({ file, onSuccess }) => {
  try {
    // 模拟上传过程
    const formData = new FormData();
    formData.append('file', file);
    const token = sessionStorage.getItem("token") || "";
    // 实际API请求
    const response = await fetch('http://localhost:8090/api/upload/file', {
      method: 'POST',
      headers: {
        Authorization: token,
      },
      body: formData,
    });
    const res = await response.json();
    if(res.code === 0){
      message.success('头像上传成功！');
      form.avatar = res.data.url;
    }
  } catch (error) {
    message.error('头像上传失败');
  }
};

// 提交表单
const handleSubmit = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    const address = [...form.region,form.address];
    delete form.region;
    delete form.address;
    const res = await updateUserInfo({
      ...form,
      address:JSON.stringify(address)
    });
    if(res.code === 0){
      message.success('个人信息更新成功');
    }
  } catch (error) {
    message.error('更新失败');
  } finally {
    fetchUserProfile();
    loading.value = false;
  }
};



</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-upload :deep(.ant-upload.ant-upload-select-picture-card) {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-text {
  margin-top: 8px;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input .ant-btn {
  width: 120px;
}
</style>